package org.springcloud.wisdom.spring_01_canteen.common.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springcloud.wisdom.spring_01_canteen.common.bean.ResponseData;
import org.springcloud.wisdom.spring_01_canteen.common.util.FileUtil;
import org.springcloud.wisdom.spring_01_canteen.dishes.fordishes.Dishes;
import org.springcloud.wisdom.spring_01_canteen.dishes.fordishes.DishesDao;
import org.springcloud.wisdom.spring_01_canteen.login.dao.Clogindao;
import org.springcloud.wisdom.spring_01_canteen.login.entity.Mall;
import org.springcloud.wisdom.spring_01_canteen.login.service.Cloginservice;
import org.springcloud.wisdom.spring_01_canteen.login.service.CmallService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

// 商家注册（有上传运营执照）
@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${myfile.user.photopath}")
    private String savePath;

    @Autowired
    private Clogindao clogindao;
    @Autowired
    private DishesDao dishesDao;

    @Autowired
    private CmallService cmallService;
    //上传运营执照审核
    @PostMapping("/addWithPhoto")
    public ResponseData<String> addWithPhoto(@RequestParam("userphoto") MultipartFile file,
                                             @RequestParam("mname") String mname,
                                             @RequestParam("mpassword") String mpassword,
                                             @RequestParam("mphone") String mphone,
                                             @RequestParam("canteen") String canteen,
                                             @RequestParam("mrange") String mrange,
                                             HttpServletRequest request) {

        boolean result = false;
        String fileUrl = null;
        if (!file.isEmpty()) {

            String newFileName =
                    new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())
                    + FileUtil.getExtName(file.getOriginalFilename());

            // 定义上传文件的目录
            // 获取存储到服务器的路径文件夹
            ApplicationHome home = new ApplicationHome(getClass());
            String rootPath = home.getDir().getAbsolutePath();
            String filepath = rootPath + "/static/upload/";
            // 判断目录是否存在
            FileUtil.mkDir(filepath);
            // 创建文件对象参数 1 父路径，参数 2 文件名
            File savefile = new File(filepath, newFileName);

            // 保存到数据库的相对路径，例如：/upload/xxxxxxx.jpg
            fileUrl = "/upload/" + newFileName;

            try {
                file.transferTo(savefile);
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
                result = false;
            }
        }

        // 检查用户名是否重复
        if (cmallService.checkMnameExists(mname)) {
            return new ResponseData<>(601, "用户名已存在", null);
        }

        // 保存到数据库
        Mall mall = new Mall();
        mall.setMname(mname);
        mall.setMpassword(mpassword);
        mall.setMphone(mphone);
        mall.setCanteen(canteen);
        mall.setMlicense(fileUrl);
        mall.setMrange(mrange);
        result &= clogindao.addMall(mall) > 0;

        log.error("File upload result: " + result + ", URL: " + fileUrl);
        ResponseData<String> responseData = new ResponseData<>();
        responseData.setData(fileUrl);
        if (result) {
            responseData.setErrorCode(200);
            responseData.setMsg("成功");
        } else {
            responseData.setErrorCode(605);
            responseData.setMsg("失败");
        }
        return responseData;
    }
    //根据id上传修改图片
    @PostMapping("/rephoto")
    public ResponseData<String> rePhoto(@RequestParam("userphoto")MultipartFile file,
                                        @RequestParam("did") Integer did,
                                        HttpServletRequest request){
        boolean result1 = false;
        String fileUrl1 = null;
        if (!file.isEmpty()) {

            String newFileName =
                    new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())
                            + FileUtil.getExtName(file.getOriginalFilename());

            // 定义上传文件的目录
            // 获取存储到服务器的路径文件夹
            ApplicationHome home = new ApplicationHome(getClass());
            String rootPath = home.getDir().getAbsolutePath();
            String filepath = rootPath + "/static/uploaddish/";
            // 判断目录是否存在
            FileUtil.mkDir(filepath);
            // 创建文件对象参数 1 父路径，参数 2 文件名
            File savefile = new File(filepath, newFileName);

            // 保存到数据库的相对路径，例如：/upload/xxxxxxx.jpg
            fileUrl1 = "/uploaddish/" + newFileName;

            try {
                file.transferTo(savefile);
                result1 = true;
            } catch (Exception e) {
                e.printStackTrace();
                result1 = false;
            }
        }
        //保存到数据库
        Dishes dishes=new Dishes();
        dishes.setDid(did);
        dishes.setDphotourl(fileUrl1);
        result1 &= dishesDao.update(dishes) > 0;
        log.error(fileUrl1);
        ResponseData<String> responseData = new ResponseData<>();
        responseData.setData(fileUrl1);
        if (result1){
            responseData.setErrorCode(200);
            responseData.setMsg("成功");
        }else {
            responseData.setErrorCode(605);
            responseData.setMsg("失败");
        }
        return responseData;
    }

    //添加菜品
    @PostMapping("/dish")
    public ResponseData<String> addWithDish(@RequestParam("userphoto") MultipartFile file,
                                             @RequestParam("dname") String dname,
                                             @RequestParam("dtype") String dtype,
                                             @RequestParam("dprice") String dprice,
                                             @RequestParam("dfood") String dfood,
                                            @RequestParam("mallid") Integer mallid,
                                             HttpServletRequest request) {

        boolean result = false;
        String fileUrl = null;
        if (!file.isEmpty()) {

            String newFileName =
                    new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())
                            + FileUtil.getExtName(file.getOriginalFilename());

            // 定义上传文件的目录
            // 获取存储到服务器的路径文件夹
            ApplicationHome home = new ApplicationHome(getClass());
            String rootPath = home.getDir().getAbsolutePath();
            String filepath = rootPath + "/static/upload/";
            // 判断目录是否存在
            FileUtil.mkDir(filepath);
            // 创建文件对象参数 1 父路径，参数 2 文件名
            File savefile = new File(filepath, newFileName);

            // 保存到数据库的相对路径，例如：/upload/xxxxxxx.jpg
            fileUrl = "/upload/" + newFileName;

            try {
                file.transferTo(savefile);
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
                result = false;
            }
        }

        // 保存到数据库
        Dishes dishes = new Dishes();
        dishes.setDname(dname);
        dishes.setDtype(dtype);
        dishes.setDprice(dprice);
        dishes.setDphotourl(fileUrl);
        dishes.setDfood(dfood);
        dishes.setMallid(mallid);
        result &= dishesDao.adddish(dishes) > 0;

        log.error("File upload result: " + result + ", URL: " + fileUrl);
        ResponseData<String> responseData = new ResponseData<>();
        responseData.setData(fileUrl);
        if (result) {
            responseData.setErrorCode(200);
            responseData.setMsg("成功");
        } else {
            responseData.setErrorCode(605);
            responseData.setMsg("失败");
        }
        return responseData;
    }
}